package com.example.myweather;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager viewpager;
    private RadioGroup radioGroup;

    private List<Fragment>fragments=new ArrayList<>();
    private  List<View>buttons;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewpager=(ViewPager)findViewById(R.id.viewpager2);
        radioGroup=(RadioGroup)findViewById(R.id.naniu);

        WeatherCityfragment weatherCityfragment =new WeatherCityfragment();
        CityFragment cityFragment =new CityFragment();
       Trendfragment trendfragment=new Trendfragment();
       Weatherfragment weatherfragment=new Weatherfragment();

        fragments.add(weatherfragment);
        fragments.add(trendfragment);
        fragments.add(weatherCityfragment);
        fragments.add(cityFragment);

        viewpager.setAdapter(new MyAdapter(getSupportFragmentManager()));

         buttons=radioGroup .getTouchables();
         viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
             @Override
             public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

             }

             @Override
             public void onPageSelected(int position) {
                 RadioButton radioButton=(RadioButton)buttons.get(position);
                 radioButton.setChecked(true);
             }

             @Override
             public void onPageScrollStateChanged(int state) {

             }
         });
         radioGroup.setOnCheckedChangeListener((group, checkedId) ->{
            if(checkedId==R.id.radioButton){
                viewpager.setCurrentItem(0);
            }else if  (checkedId==R.id.radioButton2){
                viewpager.setCurrentItem(1);
            }else if (checkedId==R.id.radioButton4){
                viewpager.setCurrentItem(2);
            }else if (checkedId==R.id.radioButton5){
                viewpager.setCurrentItem(3);
            }
        } );
    }

    private class  MyAdapter extends FragmentPagerAdapter{
        protected MyAdapter(FragmentManager supportFragmentManager){
            super(supportFragmentManager);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

}